package com.leyou.user.web;

import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/13 0013
 * Time: 14:01
 */

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "校验用户数据是否可用，如果数据库不存在则可用")
    @ApiResponses({
            @ApiResponse(code = 200, message = "校验结果有效，true或false代表可用或不可用"),
            @ApiResponse(code = 400, message = "请求参数有误，比如type不是指定值")
    })
    @GetMapping("check/{data}/{type}")
    public ResponseEntity<Boolean> checkUser(
            @ApiParam(value = "检验的数据", example = "jack") @PathVariable("data") String data,
            @ApiParam(value = "type 类型", example = "1:用户名 2:手机号") @PathVariable("type") Integer type) {
        return ResponseEntity.ok(userService.checkUser(data, type));
    }

    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code) {
        if (result.hasErrors()) {
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining("、"));
            throw new LyException(400, msg);
        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("query")
    public ResponseEntity<UserDTO> queryUserByUserNameAndPassword(@RequestParam("username") String username, @RequestParam("password") String password) {
        return ResponseEntity.ok(userService.queryUserByUserNameAndPassword(username, password));
    }

    @PostMapping("code")
    public ResponseEntity<Void> code(@RequestParam("phone") String phone) {
        userService.code(phone);
        return ResponseEntity.status(204).build();
    }
}
